'use strict'

process.chdir(__dirname)

const psqlorm = require('psqlorm')
const pg = require('pg')
const cfg = require('./config/config')
const fs = require('fs')

function fmtFileName (a) {

  if (a.indexOf('/') > 0) {
    let paths = a.split('/').filter(p => p.length > 0)
    if (paths.length > 1) {
      a = paths[ paths.length - 1 ]
    }
  }

  if (a.indexOf('.js') < 0) {
    return `${a}.js`
  }

  return a
}

let filelist = []

let dbdir = './model'

let schema = cfg.dbschema

if (process.argv.length > 2) {
  for (let i = 2; i < process.argv.length; i++) {

    if (process.argv[i].indexOf('--dir=') === 0) {
      dbdir = process.argv[i].substring(6)
      continue
    }

    if (process.argv[i].indexOf('--schema=') === 0) {
      schema = process.argv[i].substring(9)
      continue
    }

    if (process.argv[i].indexOf('--') === 0) {
      continue
    }

    filelist.push( fmtFileName(process.argv[i]) )
  }
}

let pdb = new pg.Pool(cfg.dbconfig)
let pqorm = new psqlorm(pdb)

pqorm.setSchema(schema)

;(async () => {
  let mobj = null;
  
  try {
    
    await pdb.query(`create schema if not exists ${schema}`)

    let m

    let files = fs.readdirSync(dbdir, {withFileTypes: true})

    for (let i = 0; i < files.length; i++) {
      if (!files[i].isFile()) {
        continue
      }
      
      if (files[i].name.indexOf('.js') < 0) {
        continue
      }

      if (files[i].name[0] === '!' || files[i].name[0] === '_') {
        continue
      }

      if (filelist.length > 0 && filelist.indexOf(files[i].name) < 0) {
        continue
      }

      m = require(`${dbdir}/${files[i].name}`)

      if (!m || !m.__proto__ || m.__proto__.name !== 'PostgreModel')
        continue

      mobj = new m(pqorm)

      if (!mobj.tableName || !mobj.table || typeof mobj.table !== 'object' || !mobj.table.column || mobj.syncLock) {
        continue
      }
  
      await mobj.sync(true, true, true)

      if (mobj.syncinit && typeof mobj.syncinit === 'function') {
        await mobj.syncinit();
      }

    }
  
  } catch (err) {
    console.error(err)
  } finally {
    pdb.end()
  }
  
})();
